/**
 * 
 */
package com.lanswon.qzsmk.service.cardManageService.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ch.qos.logback.classic.Logger;

import com.lanswon.common.card.CardUtil;
import com.lanswon.qzsmk.base.AccountContants;
import com.lanswon.qzsmk.base.CardContants;
import com.lanswon.qzsmk.base.DwzPage;
import com.lanswon.qzsmk.base.ErrorInfoContants;
import com.lanswon.qzsmk.base.HttpContants;
import com.lanswon.qzsmk.base.PathContants;
import com.lanswon.qzsmk.dao.BatchCollectionMapper;
import com.lanswon.qzsmk.dao.BusiParamMapper;
import com.lanswon.qzsmk.dao.BusinessMapper;
import com.lanswon.qzsmk.dao.CardArchiveMapper;
import com.lanswon.qzsmk.dao.CardControlMapper;
import com.lanswon.qzsmk.dao.CardDataMapper;
import com.lanswon.qzsmk.dao.CardManageMapper;
import com.lanswon.qzsmk.dao.CardPeopleMapper;
import com.lanswon.qzsmk.dao.CardPhysicsTypeMapper;
import com.lanswon.qzsmk.dao.CardProdunctDefinitionMapper;
import com.lanswon.qzsmk.dao.CardTypeMapper;
import com.lanswon.qzsmk.dao.CertMapper;
import com.lanswon.qzsmk.dao.CertificateMapper;
import com.lanswon.qzsmk.dao.CollAttachMapper;
import com.lanswon.qzsmk.dao.CollectionMapper;
import com.lanswon.qzsmk.dao.CorpTmpMapper;
import com.lanswon.qzsmk.dao.CorporationMapper;
import com.lanswon.qzsmk.dao.FeeRulesMapper;
import com.lanswon.qzsmk.dao.NationMapper;
import com.lanswon.qzsmk.dao.PersonalMapper;
import com.lanswon.qzsmk.dao.PersonalRepeatTmpMapper;
import com.lanswon.qzsmk.dao.PersonalTmpMapper;
import com.lanswon.qzsmk.dao.PhotoMapper;
import com.lanswon.qzsmk.dao.TransGlideMapper;
import com.lanswon.qzsmk.dao.TxnDtlMapper;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.exception.ErrorCode;
import com.lanswon.qzsmk.exception.SystemException;
import com.lanswon.qzsmk.listener.ListenerProject;
import com.lanswon.qzsmk.model.ActiveUser;
import com.lanswon.qzsmk.model.BatchCollection;
import com.lanswon.qzsmk.model.Business;
import com.lanswon.qzsmk.model.CardControl;
import com.lanswon.qzsmk.model.CardData;
import com.lanswon.qzsmk.model.CardManage;
import com.lanswon.qzsmk.model.CardPeople;
import com.lanswon.qzsmk.model.CardProdunctDefinition;
import com.lanswon.qzsmk.model.Cert;
import com.lanswon.qzsmk.model.CollAttach;
import com.lanswon.qzsmk.model.Collection;
import com.lanswon.qzsmk.model.CorpTmp;
import com.lanswon.qzsmk.model.Corporation;
import com.lanswon.qzsmk.model.FeeRules;
import com.lanswon.qzsmk.model.Personal;
import com.lanswon.qzsmk.model.PersonalRepeatTmp;
import com.lanswon.qzsmk.model.PersonalTmp;
import com.lanswon.qzsmk.model.Photo;
import com.lanswon.qzsmk.model.TransGlide;
import com.lanswon.qzsmk.model.TxnDtl;
import com.lanswon.qzsmk.service.cardManageService.ApplyCardService;
import com.lanswon.qzsmk.util.CitizenCardNoGeneratorUtil;
import com.lanswon.qzsmk.util.CommonUtil;
import com.lanswon.qzsmk.util.CopyBean;
import com.lanswon.qzsmk.util.Excel;
import com.lanswon.qzsmk.util.ExportExcel;
import com.lanswon.qzsmk.util.FileUtil;
import com.lanswon.qzsmk.util.IMG;
import com.lanswon.qzsmk.util.SequenceNumberUtil;
import com.lanswon.qzsmk.util.SpellHelper;
import com.lanswon.qzsmk.util.ValidateDataUtil;
import com.lanswon.qzsmk.vo.ApplyScheduleVo;
import com.lanswon.qzsmk.vo.FeeRulesVo;
import com.lanswon.qzsmk.vo.Other;
import com.lanswon.qzsmk.vo.QueryCardDataVo;
import com.lanswon.qzsmk.vo.ResultObject;
import com.lanswon.qzsmk.vo.ResultStatus;
import com.lanswon.qzsmk.vo.ResultVo;
import com.lanswon.qzsmk.vo.ShowChargeVo;
import com.lanswon.qzsmk.vo.VoucherVo;

/**
 * @author sun
 *
 */
@Service
public class ApplyCardServiceImpl implements ApplyCardService {

	private static Logger logger = (Logger) LoggerFactory.getLogger(ApplyCardServiceImpl.class);

	@Autowired
	PersonalTmpMapper ptm; // 个人临时映射

	@Autowired
	PersonalMapper pm; // 个人正式映射

	@Autowired
	CardPeopleMapper cpm;

	@Autowired
	PhotoMapper phm; // 照片映射

	@Autowired
	PersonalRepeatTmpMapper prtm;

	@Autowired
	CorporationMapper cm; // 单位映射

	@Autowired
	BatchCollectionMapper bcm; // 批量采集映射

	@Autowired
	CardControlMapper ccm; // 卡控制映射

	@Autowired
	CardDataMapper cdm; // 卡数据映射

	@Autowired
	CardProdunctDefinitionMapper cpdm;// 卡产品定义映射

	@Autowired
	CollectionMapper colm;// 采集单映射

	@Autowired
	CollAttachMapper cam;// 采集单附件映射

	@Autowired
	BusinessMapper bm;// 业务表映射

	@Autowired
	CertMapper cem;// 凭证映射

	@Autowired
	CardManageMapper cmm;// 卡过程

	@Autowired
	CardArchiveMapper carm;// 卡档案

	@Autowired
	BusiParamMapper bpm;

	@Autowired
	CorpTmpMapper ctm;

	@Autowired
	CardTypeMapper ctma;

	@Autowired
	NationMapper nm;
	
	@Autowired
	TransGlideMapper tgm;
	
	@Autowired
	FeeRulesMapper frsm;
	
	@Autowired
	TxnDtlMapper tdm;
	
	@Autowired
	CertificateMapper cfm;
	
	@Autowired
	CardPhysicsTypeMapper cpt;
	
	/**
	 * 导出异常数据
	 */
	@Override
	@Transactional(rollbackFor=Exception.class)
	public List<String> exportData(String[] applyBatchNos,String root) throws Exception {

		// 20180116 惠国磊 增加以下3行
		if (logger.isInfoEnabled()) {
			logger.info("exportData########start()");
		}
		List<String> l = new ArrayList<>();
		// 20180131 惠国磊 以下19行 修改
		for (int i = 0; i < applyBatchNos.length; i++) {
			String applyBatchNo = applyBatchNos[i];
			List<PersonalTmp> list = ptm.queryPersonalTmpByApplyBatchNo(applyBatchNo);
			CorpTmp c = ctm.queryCorpTmpByApplyBatchNo(applyBatchNo);

//			c.setIsUrgent("y");
			if (list.size() == 0) {
				throw new ApplicationException(ErrorCode.NONE_EXCEPTION_DATA, "There is no exception data!");
			}
			String[] pp =FileUtil.generatorPath(root, PathContants.PROJECT_PATH_DOWNLOAD_EXCEPTIONDATA, applyBatchNo);
			
			
				ExportExcel.export(list, pp[0], c);
				FileUtils.forceDelete(new File(root.split("\\|")[0]+PathContants.PROJECT_PATH_EXCEL+File.separator+applyBatchNo+".xlsx"));

				// String filePath = FileUtil.generatorPath(Excel.inDir,
				// applyBatchNo);

				// 20180131 惠国磊 以下1行 修改
				// FileUtil.moveTotherFolders(filePath, Excel.outExceptionDir);
				
				
			
			
			l.add(pp[1]);
			}
		// 20180116 惠国磊 增加以下3行
		if (logger.isInfoEnabled()) {
			logger.info("exportData########end()");
		}

		

		return l;
	}

	/**
	 * 获取各申请批次的导入历史（根据查询条件）
	 * 
	 * @return
	 */
	public List<CardPeople> importHistory(String applyBatchNo, String startTime, String endTime) {
		return cpm.getAllDataByCondition(applyBatchNo, startTime, endTime);
	}

	public List<Personal> getPersonalByAplyBatchNo(String no) {
		return pm.getPersonalByApplyBatchNo(no);
	}

	/**
	 * 验证单位临时信息是否合法
	 * 
	 * @param ct
	 * @return
	 */
	private CorpTmp validCorpTmpInfo(CorpTmp ct) {
		if (StringUtils.isEmpty(ct.getCorpName())) {
			ct.setErrorInfo(ErrorInfoContants.error_empty_info);
		}
//		可追加验证
//		else if(){
//			
//		}else if(){
//					
//		}
//		else if(){
//			
//		}
		

		return ct;
	}

	/**
	 * 验证个人临时信息是否合法
	 * 
	 * @param pt
	 * @return
	 */
	private PersonalTmp validPersonalTmpInfo(PersonalTmp pt) {

		if (StringUtils.isNotEmpty(pt.getCustomerName())) {
			if (!ValidateDataUtil.isChineseName(pt.getCustomerName())) {
				pt.setErrorFlag("1");
				pt.setErrorInfo((pt.getErrorInfo() == null ? "" : pt.getErrorInfo() + ",")
						+ ErrorInfoContants.error_customerName);
			}
		}
		if (StringUtils.isNotEmpty(pt.getCurPostalcode())) {
			if (!ValidateDataUtil.isZipCode(pt.getCurPostalcode())) {
				pt.setErrorFlag("1");
				pt.setErrorInfo((pt.getErrorInfo() == null ? "" : pt.getErrorInfo() + ",")
						+ "邮编格式错误");
			}
		}
		
		
		try {
			ValidateDataUtil.checklength(pt.getContact(), ValidateDataUtil.MAX_LENGTH_50);
		} catch (ApplicationException e) {
			e.printStackTrace();
			pt.setErrorFlag("1");
			pt.setErrorInfo((pt.getErrorInfo() == null ? "" : pt.getErrorInfo() + ",")
					+ "地址字符长度超出【"+ValidateDataUtil.MAX_LENGTH_50+"】个字符");
		}
		
		try {
			ValidateDataUtil.checklength(pt.getOfficePhone(), ValidateDataUtil.MAX_LENGTH_15);
		} catch (ApplicationException e) {
			e.printStackTrace();
			pt.setErrorFlag("1");
			pt.setErrorInfo((pt.getErrorInfo() == null ? "" : pt.getErrorInfo() + ",")
					+ "办公电话字符长度超出【"+ValidateDataUtil.MAX_LENGTH_15+"】个字符");
		}
		
		try {
			ValidateDataUtil.checklength(pt.getHomePhone(), ValidateDataUtil.MAX_LENGTH_15);
		} catch (ApplicationException e) {
			e.printStackTrace();
			pt.setErrorFlag("1");
			pt.setErrorInfo((pt.getErrorInfo() == null ? "" : pt.getErrorInfo() + ",")
					+ "家庭电话字符电话长度超出【"+ValidateDataUtil.MAX_LENGTH_15+"】个字符");
		}
		
		try {
			ValidateDataUtil.checklength(pt.getCorpName(), ValidateDataUtil.MAX_LENGTH_50);
		} catch (ApplicationException e) {
			e.printStackTrace();
			pt.setErrorFlag("1");
			pt.setErrorInfo((pt.getErrorInfo() == null ? "" : pt.getErrorInfo() + ",")
					+ "单位名称字符长度超出【"+ValidateDataUtil.MAX_LENGTH_50+"】个字符");
		}
		
		if (StringUtils.isNotEmpty(pt.getPaperNo())) {
			if (!CommonUtil.isIDNumber(pt.getPaperNo())) {
				pt.setErrorFlag("1");
				pt.setErrorInfo((pt.getErrorInfo() == null ? "" : pt.getErrorInfo() + ",")
						+ ErrorInfoContants.error_paperNo);
			}
		}
		
		
		if(StringUtils.isNotEmpty(pt.getPaperNo())){
			String birthday =pt.getPaperNo().substring(6, 14);
			String databases_birthday = DateFormatUtils.format(pt.getBirthday(), "yyyy/MM/dd").replace("/", "");
			if(!birthday.equals(databases_birthday)){
				pt.setErrorFlag("1");
				pt.setErrorInfo((pt.getErrorInfo() == null ? "" : pt.getErrorInfo() + ",")
						+ ErrorInfoContants.error_paperNo_birthday);
			}
		}
		
		
		
		if (StringUtils.isNotEmpty(pt.getMobile())) {
			if (!ValidateDataUtil.isMobile(pt.getMobile())) {
				pt.setErrorFlag("1");
				pt.setErrorInfo((pt.getErrorInfo() == null ? "" : pt.getErrorInfo() + ",")
						+ ErrorInfoContants.error_mobile);
			}
		}

		if (StringUtils.isNotEmpty(pt.getEmail())) {
			if (!ValidateDataUtil.isEmail(pt.getEmail())) {
				pt.setErrorFlag("1");
				pt.setErrorInfo((pt.getErrorInfo() == null ? "" : pt.getErrorInfo() + ",")
						+ ErrorInfoContants.error_email);
			}
		}
		
		

		return pt;
	}

	/**
	 * 自检：该批次的是否有重复的证件号码
	 * 
	 * @param list
	 * @return
	 */
	public static List<PersonalTmp> getDuplicate(List<PersonalTmp> list) {
		List<PersonalTmp> l = new ArrayList<>();
		for (int i = 0; i < list.size() - 1; i++) {
			for (int j = list.size() - 1; j > i; j--) {
				if (list.get(j).getPaperNo().equals(list.get(i).getPaperNo())) {
					l.add(list.get(j));
					System.out.println("dup:" + list.get(j));
				}
			}
		}
		System.out.println("重复个数：" + l.size());
		return l;
	}

	/**
	 * 批量采集
	 */
	@Override
	@Transactional(rollbackFor=Exception.class)
	public Map<String, Object> BA(String[] paths,String root) throws Exception {
		Long start = System.currentTimeMillis();
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}

		if (activeUser == null) {
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
	
		
		
		Date now = new Date();
		Map<String, Object> mmm = new HashMap<>(); // 返回对象
		Integer applyPeopleCount = 0;// 页面凭证返回的数据 申请人数
		// 20180116 惠国磊 增加以下3行
		if (logger.isInfoEnabled()) {
			logger.info("BA########start()");
		}
		List<PersonalTmp> list = new ArrayList<>();// 表格读取的个人临时基本信息存入
		List<CorpTmp> lc = new ArrayList<>();// 表格读取的个人基本信息存入
		Set<String> exceptionApplyBatchNo = new HashSet<>();// 异常批次

		/* 申请批次号列表 */
		Set<String> applyNoList = new HashSet<>();
		/* 单位信息和批次信息的键值对 */
		Map<Corporation, BatchCollection> mm = new HashMap<>();
		// 读取excel,返回
		List<Map<CorpTmp, List<PersonalTmp>>> l = Excel.readExcelData(paths,root);
		logger.debug("批次号数量【{}】",l.size());
		
		Map<String,Boolean> ma = new HashMap<>();//批次号和个人信息和照片是否对应
		for (Map<CorpTmp, List<PersonalTmp>> map : l) {

			for (Map.Entry<CorpTmp, List<PersonalTmp>> e : map.entrySet()) {
				// 20180131 惠国磊 以下3行 修改
				if (logger.isDebugEnabled()) {
					logger.debug("e.getValue().size():" + e.getValue().size());
				}
				// 单位信息
				CorpTmp cc = e.getKey();
				lc.add(cc);

				// 员工信息
				List<PersonalTmp> lp = e.getValue();

				/* 临时表信息对象 */
				List<PersonalTmp> lp1 = new ArrayList<>();

				applyPeopleCount = lp1.size();// 该批次的申请人数

				String applyNo = "";
				for (PersonalTmp p : lp) {
					if (applyNo == "") {
						applyNo = p.getApplyBatchNo();
					}

					// 20180131 惠国磊 以下8行 增加
					if (logger.isDebugEnabled()) {
						/* 企业登记号 */
						logger.debug("企业登记号 :" + cc.getCrNo());
						/* 单位地址 */
						logger.debug("单位地址:" + cc.getCorpAddr());
						/* 单位名称 */
						logger.debug("单位名称:" + cc.getCorpName());
					}
					p.setNameSpell(SpellHelper.toHanyuPinyin(p.getCustomerName()));
					p.setCorpNo(cc.getCrNo());
					p.setCorpAddr(cc.getCorpAddr());
					p.setCorpName(cc.getCorpName());
					logger.debug(lp.size() + "------------------" + p);
					lp1.add(p);
					logger.debug("读完表格获取申请批次号【{}】",applyNo);
					applyNoList.add(applyNo);
				}

				// 验证 匹配人员和照片是否对应
				
				boolean d = IMG.validPhotos(lp1, applyNo,root);
				logger.debug(" [{}]验证 匹配人员和照片是否对应---->[{}]",applyNo,d);
				ma.put(applyNo,d);
				
				list.addAll(lp1);

			}
		}

		/* 临时表人员信息列表，更新了最大导入次数 */
		List<PersonalTmp> lll = new ArrayList<>();

		/* 临时表单位信息列表，更新了最大导入次数 */
		List<CorpTmp> lct = new ArrayList<>();

		// 设置导入次数之前，先查询上次的importCount最大值，按批次 次数然后+1

		Iterator<String> it = applyNoList.iterator();
		while (it.hasNext()) {
			String applyBatchNo = it.next();
			Integer importCount = ptm.queryImportCountByApplyBatchNo(applyBatchNo);// 查询该批次的最大导入次数
			logger.debug("获取批次号的导入次数【{}】",importCount);
			for (PersonalTmp pt : list) {// 遍历当前的申请人员信息
				if (pt.getApplyBatchNo().equalsIgnoreCase(applyBatchNo)) {
					if (importCount == null) {
						pt.setImportCount(1);
					} else {
						pt.setImportCount(importCount + 1);
					}
					lll.add(pt);
				}
			}

			Integer importCount1 = ctm.queryImportCountByApplyBatchNo(applyBatchNo);
			for (CorpTmp ct : lc) {
				if (ct.getApplyBatchNo().equalsIgnoreCase(applyBatchNo)) {
					if (importCount1 == null) {
						ct.setImportCount(1);
					} else {
						ct.setImportCount(importCount1 + 1);
					}
					lct.add(ct);
				}

			}

		}

		for (PersonalTmp ppp : lll) {
			logger.debug("解密客户姓名【{}】",ppp.getCustomerName());
		}

		// 导入前，检查excel表是否有对应的图片文件夹，并且excel人员数量和身份信息的 与图片对应验证
		// excel 和photo 之间对应验证

		// excel 和 excel 之间的验证

		// excel 无重复验证

		// excel导入临时表，员工信息
		logger.info("---------------- excel导入临时表-----------------");

		ctm.batchInsert(lct);
		ptm.batchInsert(lll);

		logger.info("---------------- 验证数据-----------------");

		//查询所有 正式人员
		List<Personal> allPersonal = pm.queryAll();
		
		List<Corporation> lcorp = new ArrayList<>();// 存入正确的单位信息
		List<CorpTmp> lcorpt = new ArrayList<>();// 存入正确的单位信息
		List<Personal> lps = new ArrayList<>();
//		List<PersonalTmp> lper = new ArrayList<>();// 准备存入正式表 的正确数据

		// 检验数据格式（个人信息临时表和单位信息临时表） 异常批次号存入-exceptionApplyBatchNo
		logger.info("---------------ddddddd--------------" + applyNoList.size());
		it = applyNoList.iterator();
		Set<String> set = new HashSet<>();
		while (it.hasNext()) {

			String ans = it.next();

			List<PersonalTmp> lp = ptm.queryPersonalTmpByApplyBatchNo(ans);
			

			List<PersonalTmp> llll = getDuplicate(lp);// 自检重复性
			logger.debug("批次号【{}】重复个数*******************[{}]",ans , llll.size());
			if (llll.size() > 0) {
				for (PersonalTmp pt : llll) {
					exceptionApplyBatchNo.add(ans);
					pt.setErrorFlag("1");
					if(pt.getErrorInfo() == null)
						pt.setErrorInfo(ErrorInfoContants.error_duplication_data);
					else
						pt.setErrorInfo(pt.getErrorInfo() + "," + ErrorInfoContants.error_duplication_data);
					ptm.update(pt);
				}
			}else{
				//去数据库检重
//				for(PersonalTmp pt:lp){
//					for(Personal per:allPersonal){
//						if(pt.getPaperType().equals(per.getPaperType()) && pt.getPaperNo().equals(per.getPaperNo())){
							//如果存在---检查是否办过该卡
							
//							pt.setErrorFlag("1");
//							if(pt.getErrorInfo() == null)
//								pt.setErrorInfo(ErrorInfoContants.error_duplication_data_personal);
//							else
//								pt.setErrorInfo(pt.getErrorInfo() + "," + ErrorInfoContants.error_duplication_data_personal);
//							ptm.update(pt);
//							exceptionApplyBatchNo.add(ans);
//						}
//					}
//				}
				
			}
			
			
			

			CorpTmp ct = ctm.queryCorpTmpByApplyBatchNo(ans);
			ct = validCorpTmpInfo(ct);
			for (PersonalTmp pet : lp) {
				pet = validPersonalTmpInfo(pet);

				System.out.println(pet.getErrorInfo() + "----检查数据是否错误");
				System.out.println(ct == null);

				if ("1".equals(pet.getErrorFlag())) {
					logger.debug("添加异常批次【{}】",ans);
					exceptionApplyBatchNo.add(ans);
					ptm.update(pet);
				}
				if (StringUtils.isNotEmpty(ct.getErrorInfo())) {
					logger.debug("添加异常批次【{}】",ans);
					exceptionApplyBatchNo.add(ans);
					ctm.update(ct);
				}
				if ("1".equals(pet.getErrorFlag()) || StringUtils.isNotEmpty(ct.getErrorInfo()) || llll.size() > 0) {
					logger.info(pet.getPaperNo() + "," + pet.getErrorInfo() + "申请批次号---去除异常批次-----" + ans + ","
							+ pet.getErrorFlag() + "," + ct.getErrorInfo() + "," + llll.size());
//					it.remove();
				} else {
					logger.debug("验证是否已办过该卡产品--批次【{}】,证件【{}】",ans,pet.getPaperNo());
					ResultVo vo = checkIsCardProductbyPaperNo(pet.getPaperType(), pet.getPaperNo(), ans.substring(0, 2));
					
					int code = vo.getResultStatus().getCode();
					logger.debug("状态码【{}】",code);
						if (code == 3 || code == 4) {
							logger.debug("fuck!!!!你已经办过了");
							pet.setErrorFlag("1");
							pet.setErrorInfo((pet.getErrorInfo() == null ? "" : pet.getErrorInfo() + ",")
									+ ErrorInfoContants.error_duplication_cardpCard);
							ptm.update(pet);
							logger.debug("添加异常批次【{}】",ans);
							exceptionApplyBatchNo.add(ans);
//							it.remove();
						}

					set.add(ct.getApplyBatchNo());
					// lcorpt.add(ct);
				}
			}

		}
		
		Iterator<String> iii= applyNoList.iterator();
		Iterator<String> ie = exceptionApplyBatchNo.iterator();
		while(iii.hasNext()){
			String no = iii.next();
			while(ie.hasNext()){
				String nn = ie.next();
				if(no.equals(nn)){
					iii.remove();
				}
			}
		}
		
		
		
		
		for (String applyNo : set) {
			logger.info("申请批次号--------" + applyNo);

			// 存入正确的单位信息
			lcorpt.add(ctm.queryCorpTmpByApplyBatchNo(applyNo));
		}

		List<BatchCollection> lba = new ArrayList<>();

		logger.info(it.hasNext() + "---------------嘎嘎嘎--------------" + applyNoList.size());

		Map<String,List<PersonalTmp>> m1m = new HashMap<>();
		Map<String,List<Personal>> m2m = new HashMap<>();

		// 个人信息临时表和单位信息临时表 的数据 合法后，继续检验个人信息
		it = applyNoList.iterator();
		while (it.hasNext()) {
			String ans = it.next();
			// 检验数据的重复性与正式表比较,(重复数据转存PersonalRepeatTmp， 并在lp中移除
			List<PersonalTmp> lp = ptm.queryPersonalTmpByApplyBatchNo(ans);
			System.out.println(ans + "////////////////////////////////");

			logger.info("-----------------批次号【{}】-------临时人员信息【{}】----------" ,ans,lp.toString());

			/* 批量采集表 */
			BatchCollection bc = new BatchCollection();
			bc.setApplyBatchNo(ans);
			int index = ans.indexOf("_");
			/* 卡产品的字符串 */
			String cardpCode = ans.substring(0, index);
			bc.setCardPCode(cardpCode);

			// 20180129 惠国磊 以下3行 修改
			if (logger.isDebugEnabled()) {
				logger.debug("产品类型代码：" + cardpCode);
			}
			bc.setCollBranchName(activeUser.getBranchName());// 采集网店名称
			bc.setCollBranchNo(activeUser.getBranchNo());// 采集网点编号
			bc.setCrtDate(now);
			bc.setCrtOperator(activeUser.getUserNo().toString());
			// bc.setIsUrgent(cc.getIsUrgent());
			bc.setLastDate(now);
			bc.setLastOperator(activeUser.getUserNo().toString());
			// bc.setOriginType("1");// 来源，后面可能要改成code1,code2...
			bc.setRecordNum(lp.size());// 记录申请数量
			Calendar ccc = Calendar.getInstance();
			ccc.setTime(now);
			ccc.add(Calendar.DAY_OF_MONTH, bpm.queryBusiParamByCardPCode(cardpCode).getReleaseDays());// 今天+n天===预计领卡日期
			bc.setApplyDate(ccc.getTime());

			Iterator<PersonalTmp> itpet = lp.iterator();
			while (itpet.hasNext()) {
				PersonalTmp pet = itpet.next();
				logger.debug("临时信息【{}】",pet);
				Personal ppp = pm.queryPersonalByPaperNo(pet.getPaperType(), pet.getPaperNo());
				if (ppp != null) {// 如果存在正式信息，就更新信息，并且将该临时信息置入重复信息表里
//					logger.debug("ppp批次【{}】已经存在重复信息【{}】",ppp.getApplyBatchNo(),ppp);
//					Personal ppp1 = (Personal) CopyBean.copyA2b(pet, ppp);
//					logger.debug("ppp批次【{}】更新后的重复信息【{}】",ppp.getApplyBatchNo(),ppp);
//					pm.update(ppp1);
					PersonalRepeatTmp prt = new PersonalRepeatTmp();
					prt = (PersonalRepeatTmp) CopyBean.copyA2b(pet, prt);
					prt.setCustomerNo(ppp.getCustomerNo());
					prtm.insert(prt);
					itpet.remove();
				}

			}
			m1m.put(ans, lp);
//			lper.addAll(lp);

			// 单位信息，如果正式表已经存在，就不保存入正式表
			CorpTmp corp = ctm.queryCorpTmpByApplyBatchNo(ans);

			Corporation  corporation= cm.queryCorporationByCorpNo(corp.getCorpNo());
			if (corporation != null) {
				logger.debug("单位信息，如果正式表已经存在，就不保存入正式表,单位【{}】",corp);
				lcorpt.remove(corp);
			}
			logger.debug("lcorpt===>" + lcorpt);

			bc.setCorpCode(corp.getCorpNo());
			lba.add(bc);
		}

		logger.info("-----------------临时表对象转换正式表对象-----------------");

//		for (PersonalTmp ptmp : lper) {
//			Personal per = new Personal();
//			per = (Personal) CopyBean.copyA2b(ptmp, per);
//			lps.add(per);
//		}
		
		for(Entry<String,List<PersonalTmp>> e:m1m.entrySet()){
			List<Personal> lpo = new ArrayList<>();
			
			List<PersonalTmp> lip = e.getValue();
			for (PersonalTmp ptmp : lip) {
				Personal per = new Personal();
				per = (Personal) CopyBean.copyA2b(ptmp, per);
				lpo.add(per);
			}
			
			lps.addAll(lpo);
			m2m.put(e.getKey(), lpo);
		}
		
		
		for (CorpTmp ct : lcorpt) {
			Corporation cccc = new Corporation();
			cccc = (Corporation) CopyBean.copyA2b(ct, cccc);
			lcorp.add(cccc);
			System.out.println("=======================================" + cccc.toString());
		}

		logger.info(lcorpt.size() + "-----------------临时表插到正是表-----------------" + lcorp.size());

		for (Personal p : lps) {
			System.out.println("lps的信息" + p.toString());
		}

		logger.debug("lps==>" + lps.toString());
	
			if (lcorp.size() > 0)
				cm.batchInsert(lcorp);// 单位信息
			
			if (lps.size() > 0)
			pm.batchInsert(lps);// 个人信息
			if(lba.size()>0)
			bcm.saveBatchCollection(lba);// 批量采集信息
		
		

		// 导入图片
		logger.info("----------------开始导入图片-----------------");// 首先要排除掉已经存在的个人信息。照片就不用上传了

		Iterator<String> it1 = applyNoList.iterator();

		while (it1.hasNext()) {
			String applyNo = it1.next();
			
			
				FileUtil.moveTotherFolders(root+PathContants.PROJECT_PATH_EXCEL+File.separator+applyNo+".xlsx", 
						root+PathContants.PROJECT_PATH_EXCEL_IMPORTED);
			
			
			if(ma.get(applyNo)!= null && ma.get(applyNo)){
				Map<String, String> pathPhotoMap = new HashMap<>();

//				FtpUtil.createFile(GlobalVariableManager.FTP_URL, GlobalVariableManager.FTP_PORT,
//						GlobalVariableManager.FTP_USER, GlobalVariableManager.FTP_PASSWORD, "/resource/batchPhotosed/"
//								+ applyNo);
				Map<String, String> map = IMG.batchUploadPhotosByApplyBatchNo(root, applyNo);
				for (Map.Entry<String, String> e : map.entrySet()) {// 默認暫且身份证信息,遍历的是图片的上传路径，图片名以证件号码命名
					Photo p = new Photo();
					// p.setBillNo(billNo);//批量方式，没有采集单号
					p.setCrtDate(now);
					p.setCrtOperator(activeUser.getUserNo().toString());
					logger.debug(e.getKey() + ":" + e.getValue());
					Personal pe = pm.queryPersonalByPaperNo(null, e.getKey());
					p.setCustomerNo(pe.getCustomerNo());
					p.setLastDate(now);
					p.setPaperNo(e.getKey());
					p.setLastOperator(activeUser.getUserNo().toString());
					p.setPaperType(pe.getPaperType());
					p.setPhoto(e.getValue());
					p.setRemark("批量存儲照片哦 ，，，");
					String photoSuffix = e.getValue().substring(e.getValue().indexOf("."));
					p.setPhotoType(CardContants.getFileTypeCodeByFileSuffix(photoSuffix));// z照片类型
																							// 1.JPG
																							// 2.GIF
																							// 3.BMP
					phm.savePhoto(p);

				logger.info("----------------导入图片完成-----------------");
				}
			}
		}
			// 获取重复个人信息表的数据（正式表已经存在的个人信息，已经办过卡，什么卡不知道）

			logger.info("----------------保存卡数据信息-----------------" + applyNoList.size());
		
			
			for(Entry<String,List<Personal>> e:m2m.entrySet()){
				
				
			
			String apply = e.getKey();
			int index = apply.indexOf("_");
			String cardpCode = apply.substring(0, index);// 卡产品
			int index1 = apply.indexOf("_", index + 1);
			String cardPhysicsType = apply.substring(index + 1, index1);// 卡类型(物理)

			CardProdunctDefinition cpd = cpdm.queryCardPCode(cardpCode);// 卡产品定义
			logger.debug("apply===>" + apply);
			Corporation cor =new Corporation();
			for(BatchCollection batchCollection:lba){
				if(batchCollection.getApplyBatchNo().equals(apply)){
					 cor = cm.queryCorporationByCorpNo(batchCollection.getCorpCode());
					break;
				}
			}  
//			Corporation cor = cm.queryCorporationByApplyBatchNo(apply);// 根据批次号查询单位
			logger.debug("------测试查询批次申请表--------");
//			BatchCollection bcc = bcm.queryBatchCollectionByApplyBatchNo(apply);
//			logger.debug("----[{}]--测试查询批次申请表-------[{}]-",bcc.getCorpCode(),bcc);
//			logger.debug("查询单位【{}】",cm.queryCorporationByCode(bcc.getCorpCode()));
//			logger.debug("单位==>" + cor);
			// 查询是否能办该卡
			// 根据批次号获取重复个人信息表的数据（正式表已经存在的个人信息，已经办过卡，什么卡不知道）
			List<PersonalRepeatTmp> lk = prtm.queryInfoByApplyBatchNo(apply);

			List<Personal> lp = e.getValue();
//			List<Personal> lp = pm.getPersonalByApplyBatchNo(apply);
			for(PersonalRepeatTmp prr:lk){
				Personal pa = new Personal();
				pa = (Personal) CopyBean.copyA2b(prr, pa);
				lp.add(pa);
			}
			
			
			List<CardData> listCardData = new ArrayList<>();
			List<Cert> listCert = new ArrayList<>();
			List<Business> listBusiness = new ArrayList<>();
			List<CardManage> listCardManage = new ArrayList<>();
			List<CardControl> listCardControl = new ArrayList<>();

			Calendar ccc = Calendar.getInstance();
			ccc.setTime(now);
			ccc.add(Calendar.DAY_OF_MONTH, bpm.queryBusiParamByCardPCode(cardpCode).getReleaseDays());// 今天+n天===预计领卡日期

			String prefix = CitizenCardNoGeneratorUtil.getCardNoPrefix(cardpCode, cardPhysicsType);
			int flag =0;
			for (Personal p : lp) {
				flag ++;
				// 保存卡数据信息
				CardData c = new CardData();
				c.setCustomerNo(p.getCustomerNo());// 客户编号
				logger.info("-------------------------------------------------------mmp--------------------------------------------------------------------");
				// String citizenCardNo =
				// CitizenCardNoGeneratorUtil.generatorKey(prefix);
//				String citizenCardNo = generatorCardNo(prefix);
//				// 20180131 惠国磊 以下一行 修改
//				logger.debug("citizenCardNo=========>" + citizenCardNo);
//				c.setCitizenCardNo(citizenCardNo);// 市民卡号
				c.setCardpCode(cardpCode);// 卡产品
				c.setCardTypecode(cpd.getCardTypeCode());// 卡类型
				c.setCardPhysicalType(cardPhysicsType);
				if(ma.get(apply) != null && ma.get(apply)){
					Photo photo = phm.queryPhotoByCustomerNo(p.getCustomerNo());
					c.setPhotoId(photo.getPhotoId());// 通过客户编号 查询照片表id
				}
				c.setCardValidTime(CommonUtil.willDate(now, cpd.getCardValidTime()));
				c.setFlag(flag);
				listCardData.add(c);

				// 业务流水表
				Business b = new Business();
				b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
				// b.setAgentName(agentName);//代理人姓名
				// b.setAgentPaperNo(agentPaperNo);//代理人证件号码
				// b.setAgentPapertype(agentPapertype);//代理人证件类型
				// b.setAgentPhone(agentPhone);// 代理人联系电话
				b.setBatchNo(apply);// 批次号
				b.setBusiNum(0);// 业务数量啥子吆
//				 b.setCardControlId(cc.getCardControlId());// 卡控制号 批量用不上
				b.setCardpCode(cardpCode);// 卡产品
				// b.setCertNo(certNo);/凭证编号

//				b.setCorpNo(cor.getCorpNo());// 单位编号 批量办理时使用
				 b.setCustomerNo(p.getCustomerNo());// 客户编号
				b.setRemark("這是批量申請業務表");// 备注
				// b.setRptDate(rptDate);//轧帐日期
				// b.setRptFlag(rptFlag);//轧帐标识
				b.setTellerNo(activeUser.getUserNo().toString());// 柜员号
				// b.setTransAuthId("业务授权人编号001");// 业务授权人编号
				// b.setTransAuthName("业务授权人编号-赵铁柱");// 业务授权人姓名
				// b.setTransCode(transCode);//交易代码
				// b.setTransDate(transDate);//交易日期
				b.setFlag(flag);
				listBusiness.add(b);
				
				
				// 凭证表
				Cert ce = new Cert();
				ce.setCertNo(SequenceNumberUtil.generatorCertNo());
//				 ce.setAgentName();//代领人的信息，领卡的时候在填写
//				 ce.setAgentPaperNo(agentPaperNo);
//				 ce.setAgentPapertype(agentPapertype);
				ce.setBranch(activeUser.getBranchName());// 网点名称
				ce.setBranchNo(activeUser.getBranchNo().toString());// 网点编号
				 ce.setBusinessNo(b.getBusinessNo());//业务流水号
//				 ce.setCardControlId(cc.getCardControlId());
				ce.setCertType(CardContants.BATCH_APPLICATION);// 凭证类型 1 单笔申请 2 批量申请
																// 3 出库配送 4 单笔发卡 5
																// 批量发卡
				ce.setCardpCode(cardpCode);// 卡产品代码
				ce.setCardTypecode(cpd.getCardTypeCode());// 卡类型代码 1.标准卡 2.记名衍生卡
															// 3.非记名衍生卡
				ce.setCorpCode(cor.getCorpNo());// 单位编号
				ce.setCorpName(cor.getCorpName());// 单位名称
				ce.setCrtDate(now);
				ce.setCrtOperator(activeUser.getUserNo().toString());
				//ce.setData("打印凭证数据 ");// 打印凭证数据
				ce.setLastDate(now);
				ce.setLastOperator(activeUser.getUserNo().toString());
				 ce.setName(p.getCustomerName());// 持卡人姓名
				 ce.setPaperNo(p.getPaperNo());
				 ce.setPaperType(p.getPaperType());
				ce.setPrintCount(0);// 打印次数
				ce.setTransCode("批量申请");//交易代码
				ce.setFlag(flag);
				listCert.add(ce);
				
				b.setCertNo(ce.getCertNo());

				// 卡过程信息
				CardManage cme = new CardManage();
				cme.setProcessId(UUID.randomUUID().toString().replace("-", ""));
				cme.setApplyBranch(activeUser.getBranchName());
				cme.setApplyBranchNo(activeUser.getBranchNo());
				cme.setApplyDate(now);
				cme.setApplyTellerNo(activeUser.getUserNo().toString());
				cme.setBusinessNo(b.getBusinessNo());
				cme.setCertNo(ce.getCertNo());
				// cme.setProcessCode(CardContants.CARD_PROC_APPLY);
				 cme.setProcessName("申请卡片");
//				cme.setCitizenCardNo(citizenCardNo); 
				// cme.setCardpCode(cardpCode);// 卡产品
				// cme.setCardTypecode(cpd.getCardTypeCode());// 卡类型
				// cme.setCardPosition(CardContants.CARD_POSITION_NO_STORAGE);
				 cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
				cme.setApplyWay(CardContants.CLAIM_METHOD_COMPANY);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
				cme.setFlag(flag);
				listCardManage.add(cme);

				// 卡控制信息
				CardControl cc = new CardControl();
				
				cc.setApplyDate(ccc.getTime());// 预计林卡日期
				cc.setCurrProcId(cme.getProcessId());
				// cc.setCardDate(cardDate);//制卡日期
				cc.setCardPosition(CardContants.CARD_POSITION_NO_STORAGE);// 位置未入库，还没生产呢
				cc.setCardStatus(CardContants.CARD_STATE_DISABLED);// 卡状态未启用
				cc.setApplyBatchNo(p.getApplyBatchNo());
				cc.setCrtDate(now);
				cc.setCrtOperator(activeUser.getUserNo().toString());
				cc.setLastDate(now);
				cc.setLastOperator(activeUser.getUserNo().toString());
				cc.setDmgFlag(CardContants.CARD_UNDAMAGED);// 卡损坏状况
				cc.setBlacklistFlag(CardContants.BLACKLIST_FLAG_NORMAL);											// 0-未损坏，1-非人为损坏，2-人为损坏
				// cc.setLogoutDate(logoutDate);//注销日期
				// cc.setLogoutReason(logoutReason);//注销原因

				// cc.setReleaseDate(ccc.getTime());//发卡日期
				cc.setRemark("这是备注--卡控制表");
				cc.setApplyType(CardContants.APPLY_TYPE_FIRST);
				cc.setClaimStatus(CardContants.CLAIM_STATUS_APPLY);
				cc.setFlag(flag);
				listCardControl.add(cc);
			}
			
			cdm.batchInsert(listCardData);
			cmm.batchInsert(listCardManage);
			
			for(CardControl cc:listCardControl){
				for(CardData cd :listCardData){
					if(cd.getFlag() == cc.getFlag()){
						cc.setCardDataId(cd.getCardDataId());
						break;
					}
				}
				
				
			}
			
			
			
			ccm.batchInsert(listCardControl);
			
			for(CardControl cc:listCardControl){
				
				for(Cert cert:listCert){
					if(cert.getFlag() == cc.getFlag()){
						cert.setCardControlId(cc.getCardControlId());
						break;
					}
				}
				
				for(Business b:listBusiness){
					if(cc.getFlag() == b.getFlag()){
						b.setCardControlId(cc.getCardControlId());
						break;
					}
				}
			}
			
			
			bm.batchInsert(listBusiness);
			cem.batchInsert(listCert);
			
			
			// 凭证表
			Cert ce = new Cert();
			ce.setCertNo(SequenceNumberUtil.generatorCertNo());
			// ce.setAgentName(agentName);//代领人的信息，领卡的时候在填写
			// ce.setAgentPaperNo(agentPaperNo);
			// ce.setAgentPapertype(agentPapertype);
			ce.setBranch(activeUser.getBranchName());// 网点名称
			ce.setBranchNo(activeUser.getBranchNo().toString());// 网点编号
			// ce.setBusinessNo(b.getBusinessNo());//业务流水号
			// ce.setCardControlId(cc.getCardControlId());
			ce.setCertType(CardContants.BATCH_APPLICATION);// 凭证类型 1 单笔申请 2 批量申请
															// 3 出库配送 4 单笔发卡 5
															// 批量发卡
			ce.setCardpCode(cardpCode);// 卡产品代码
			ce.setCardTypecode(cpd.getCardTypeCode());// 卡类型代码 1.标准卡 2.记名衍生卡
														// 3.非记名衍生卡
			ce.setCorpCode(cor.getCorpCode());// 单位编号id
			ce.setCorpName(cor.getCorpName());// 单位名称
			ce.setCrtDate(now);
			ce.setCrtOperator(activeUser.getUserNo().toString());
			//ce.setData("打印凭证数据 ");// 打印凭证数据
			ce.setLastDate(now);
			ce.setLastOperator(activeUser.getUserNo().toString());
			// ce.setName(p.getCustomerName());// 持卡人姓名
			// ce.setPaperNo(p.getPaperNo());
			// ce.setPaperType(p.getPaperType());
			ce.setPrintCount(0);// 打印次数
			ce.setTransCode("批量申请");//交易代码
			
			FeeRulesVo fv= new FeeRulesVo();
			fv.setCardpCode(cardpCode);
			fv.setFeeType(AccountContants.FEE_TYPE_NOMINAL_FEE);
			fv.setNow(now);
			FeeRules frs = frsm.queryFeeRulesByCardPCodeAndFeeType(fv);
			BigDecimal total=null;
			if(frs != null){
			BigDecimal	unitPrice = frs.getFeeBln();
				total = unitPrice.multiply(new BigDecimal(lp.size()));
			}else{
				total=new BigDecimal("0");
			}
			String str = "{\"title\":\""+"批量申请凭证"+"\",\"type\":\""+"applyBatchRegister"+"\",\"certNo\":\""+ce.getCertNo()
			+"\",\"busType\":\""+CardContants.getCertTypeNameByCode(ce.getCertType())+"\",\"corpName\":\""+cor.getCorpName()+"\",\"cardpName\":\""+cpd.getCardpName()
			+"\",\"count\":\""+lp.size()+"\",\"fee\":\""+total+"\",\"net\":\""+activeUser.getBranchName()+"\",\"operator\":\""
			+activeUser.getUserNo().toString()+"\",\"date\":\""+DateFormatUtils.format(new Date(), "yyyy-MM-dd")+"\"}";
			ce.setData(str);
			cem.insert(ce);
			VoucherVo vv = new VoucherVo();
			vv.setCertNo(ce.getCertNo());
			vv.setBusinessTypeName(CardContants.getCertTypeNameByCode(ce.getCertType()));
			vv.setApplyPeopleCount(applyPeopleCount);
			vv.setActualApplyPeopleCount(lp.size());
			vv.setDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
			vv.setCorpName(cor.getCorpName());
			vv.setCardpName(cpd.getCardpName());
			vv.setTransactionAmount(total.toString());
			vv.setExpectCardDate(ccc.getTime());
			vv.setOperator(activeUser.getUserNo().toString());
			vv.setNet(activeUser.getBranchName());
			mmm.put(apply, vv);
			// FileUtil.moveTotherFolders(FileUtil.generatorPath(Excel.inDir,
			// apply), Excel.outDir);
		
			}

		// 20180116 惠国磊 增加以下3行
		if (logger.isInfoEnabled()) {
			logger.info("importData########end()");
		}

		
		
		
		
		logger.debug("共有【{}】个异常批次",exceptionApplyBatchNo.size());
		if (exceptionApplyBatchNo.size() > 0) {
			mmm.put("exceptionBatch", exceptionApplyBatchNo);
		}else{
			mmm.put("exceptionBatch", 0);
		}
		logger.info("!^_^!******************| 申请完成 |*****************时间差【{}】*!^_^!",System.currentTimeMillis()-start);
		return mmm;
	}

	/**
	 * 根据证件号码查询是否能办该卡产品
	 * 
	 * @param paperType
	 *            证件类型
	 * @param paperNo
	 *            证件号码
	 * @param cardProductCode
	 *            卡产品代码
	 * @return
	 */
	public ResultVo checkIsCardProductbyPaperNo(String paperType, String paperNo, String cardProductCode) {
		System.out.println("111"+paperType+paperNo);
		ResultVo rv = new ResultVo();

		ResultStatus rs = new ResultStatus();
		rs.setCode(HttpContants.RETURN_SUCCESS);
		rs.setMessage("返回成功");
		rv.setResultStatus(rs);

		ResultObject ro = new ResultObject();

		if (StringUtils.isEmpty(paperType) || StringUtils.isEmpty(paperNo) || StringUtils.isEmpty(cardProductCode)) {
			rs.setCode(ErrorCode.OBJECT_IS_NULL);
			rs.setMessage("证件类型或证件号码为空");
			rv.setResultStatus(rs);
			return rv;
		}
		
		
		Personal p = null;

		if ("00".equals(paperType)) {
			p = pm.queryPersonalByPaperNo(paperType, paperNo);
			if (p == null) {
				p = pm.queryPersonalByPaperNo("01", paperNo);
				if (p == null) {

					ro.setVariable(1);
					rv.setServiceObject(ro);
					return rv;// 能办
				} else {
					return ff(p, cardProductCode);
				}
			}
		} else if ("01".equals(paperType)) {
			p = pm.queryPersonalByPaperNo(paperType, paperNo);
			if (p == null) {
				p = pm.queryPersonalByPaperNo("00", paperNo);
				if (p == null) {
					ro.setVariable(1);
					rv.setServiceObject(ro);
					return rv;// 能办
				} else {
					return ff(p, cardProductCode);

				}
			}
		}
		p = pm.queryPersonalByPaperNo(paperType, paperNo);
		if (p == null) {
			ro.setVariable(1);
			rv.setServiceObject(ro);
			return rv;// 能办
		}

		return ff(p, cardProductCode);

	}

	private ResultVo ff(Personal p, String cardProductCode) {

		ResultVo rv = new ResultVo();

		ResultStatus rs = new ResultStatus();
		rs.setCode(HttpContants.RETURN_SUCCESS);
		rs.setMessage("返回成功");
		rv.setResultStatus(rs);

		ResultObject ro = new ResultObject();

		// 客户编号查卡档案表 只要没注销 ,没退卡，没销毁 就不能在办该卡产品
		// List<CardArchive> list =
		// carm.queryCardArchiveByCustomerNo(p.getCustomerNo());
		List<CardData> list = cdm.queryCardDataByCustomerNo(p.getCustomerNo());
		// 根据卡产品获取卡类型

		// CardProdunctDefinition cpd = cpdm.queryCardPCode(cardProductCode);
		int n = 0;
		boolean v = false;
		for (CardData ca : list) {
			CardControl cco = ccm.queryCardControlByCardDataId(ca.getCardDataId());
			v = ca.getCardpCode().equals(cardProductCode)
					&& (CardContants.BLACKLIST_FLAG_NORMAL.equals(cco.getBlacklistFlag())
					&& !CardContants.CARD_STATE_CANCELLATION_HAS_CARD.equals(cco.getCardStatus())
							&& !CardContants.CARD_STATE_CANCELLATION_NO_CARD.equals(cco.getCardStatus()) && (!CardContants.CLAIM_STATUS_CANCEL
							.equals(cco.getClaimStatus()) || !CardContants.CLAIM_STATUS_BACK.equals(cco
							.getClaimStatus())));

			logger.debug("卡产品【{}】",ca.getCardpCode().equals(cardProductCode));
			logger.debug("黑名单【{}】",CardContants.BLACKLIST_FLAG_NORMAL.equals(cco.getBlacklistFlag()));
			logger.debug("申状1【{}】",!CardContants.CARD_STATE_CANCELLATION_HAS_CARD.equals(cco.getCardStatus()));
			logger.debug("申状2【{}】",!CardContants.CARD_STATE_CANCELLATION_NO_CARD.equals(cco.getCardStatus()));
			
			
			logger.debug("-----打不过我把-------------" + v);
			if (v) {
				logger.debug("11111111111111111111");
				if (cco.getCardPosition() == CardContants.CARD_POSITION_CITIZEN) {
					n = 3;// 卡在使用中
					rs.setCode(n);
					rs.setMessage("您已成功领取该卡,请勿重复办理");
					logger.debug("222222222222222222");

				} else {
					n = 4;// 卡还在办理中
					rs.setCode(n);
					rs.setMessage("您已成功申请该卡,请勿重复申请");
					logger.debug("33333333333333");

				}
				logger.debug("4444444444444");

				rv.setResultStatus(rs);
				break;
			}
		}

		if (!v) {
			n = 2;// 能办理
			ro.setVariable(n);
			rv.setServiceObject(ro);
		}

		logger.debug("5555555555555555");

		return rv;
	}

	/**
	 * 单笔申请 加急:针对批量和定制卡 照片的获取：分为现场照相，扫描身份证
	 * 
	 * 
	 */
	@Transactional(rollbackFor=Exception.class)
	@Override
	public ResultVo singleApplication(Personal p, String cardProductCode, String cardPhysicalType){
		ResultVo rv = new ResultVo();
		ActiveUser activeUser = null;
		
		Calendar ccc = Calendar.getInstance();
		Date now   = new Date();
		ccc.setTime(now);
		ccc.add(Calendar.DAY_OF_MONTH, bpm.queryBusiParamByCardPCode(cardProductCode).getReleaseDays());// 今天+n天===预计领卡日期

		
		if(p.getPaperType()=="00" || p.getPaperType()=="01"){
			if(!CommonUtil.isIDNumber(p.getPaperNo())){
				ResultStatus rs = new ResultStatus();
				rs.setCode(ErrorCode.DATA_ILLEGALITY);
				rs.setMessage("证件号码错误");
				rv.setResultStatus(rs);
				return rv;
			}
		}
		Personal ppp = pm.queryPersonalByPaperNo(p.getPaperType(), p.getPaperNo());
		if( ppp == null){
			p.setCustomerNo(UUID.randomUUID().toString().replace("-", ""));
		}else{
			p.setCustomerNo(ppp.getCustomerNo());
		}
		
		
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}

		if (activeUser == null) {
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
			

			//保存互联网 采集单
			// 采集表
			Collection c = new Collection();
			c.setApplyDate(ccc.getTime());// 申领日期
			c.setCollBranchName(activeUser.getBranchName());// 采集网点名称
			c.setCollBranchNo(activeUser.getBranchNo());// 采集网点编号
			ResultVo r = generateCollectionNo();
			if(r.getResultStatus().getCode() == HttpContants.RETURN_SUCCESS){
				ResultObject o = (ResultObject) r.getServiceObject();
				c.setCollectionNo(o.getStr());// 采集单编号
			}else{
				ResultStatus rs = new ResultStatus();
				rs.setCode(ErrorCode.OBJECT_IS_NULL);
				rs.setMessage("采集单编号生成失败");
				rv.setResultStatus(rs);
				return rv;
			}
			c.setCustomerName(p.getCustomerName());
			c.setPaperNo(p.getPaperNo());
			c.setPaperType(p.getPaperType());
			c.setCrtDate(now);// 创建日期
			c.setCrtOperator(activeUser.getUserNo().toString());// 创建柜员号
			c.setCustomerNo(p.getCustomerNo());// 客户编号,提交个人信息时 在更新此字段
			c.setDataOrigin(CardContants.DATA_ORIGIN_INPUT_BY_HAND);// 数据来源 1读取二代身份证
																	// 2手工录入 ---参考
																	// cardcontants.class
			c.setIsPhoto("0");// 是否拍照 0否 1是 默认为否，即0否
			c.setLastDate(now);// 最后修改日期
			c.setIsUrgent("0");// 是否加急 0.不加急 1.加急 默认为0不加急
			c.setLastOperator(activeUser.getUserNo().toString());// 最后修改柜员号
			colm.insert(c);
		}
		logger.debug("客户性别【{}】", p.getGender());

		// 先检查，可办理的情况下 个人信息 不存在就保存 存在就更新
		String out = ListenerProject.contextPath;
		if ("男".equals(p.getGender())) {
			p.setGender(CardContants.GENDER_MALE);
		} else if ("女".equals(p.getGender())) {
			p.setGender(CardContants.GENDER_FEMALE);
		}

		ResultVo rrr = checkIsCardProductbyPaperNo(p.getPaperType(), p.getPaperNo(), cardProductCode);

		if (rrr.getResultStatus().getCode() == HttpContants.RETURN_SUCCESS) {
			ResultObject ro = (ResultObject) rrr.getServiceObject();

			int a = ro.getVariable();
			logger.debug("test-------------->" + a);

			if (a == 1) {

				pm.savePersonal(p);
			} else if (a == 2) {
				pm.updateByPaperTypeAndPaperNo(p);
			}

		} else if (rrr.getResultStatus().getCode() == 3) {
			ResultStatus resultStatus = new ResultStatus();
			resultStatus.setCode(ErrorCode.PERSONAL_EXIST_CARD);
			resultStatus.setMessage("客户 [" + p.getCustomerName() + "] 已经拥有此卡产品!");
			rv.setResultStatus(resultStatus);
			return rv;
		} else if (rrr.getResultStatus().getCode() == 4) {
			ResultStatus resultStatus = new ResultStatus();
			resultStatus.setCode(ErrorCode.PERSONAL_EXIST_CARD);
			resultStatus.setMessage("客户 [" + p.getCustomerName() + "] 已经申请此卡产品,正在办理中,请勿重复申请！");
			rv.setResultStatus(resultStatus);
			return rv;
		}
		
		//更新客户编号    采集单 和附件
		
//		if(activeUser.getUserId()!=99999999 ){
			colm.updateCustomerNo(p.getPaperType(), p.getPaperNo(), p.getCustomerNo());
			cam.updateCustomerNo(p.getPaperType(), p.getPaperNo());
//		}
		

		// 以下数据在发卡中写入
		// 卡数据表
		CardData cd = new CardData();
		cd.setCustomerNo(p.getCustomerNo());
		cd.setCardPhysicalType(cardPhysicalType);
		cd.setCardpCode(cardProductCode);
		CardProdunctDefinition cpd = cpdm.queryCardPCode(cardProductCode);

		// cd.setCardValidTime(cpd.getCardValidTime());
		cd.setCardTypecode(cpd.getCardTypeCode());
		// String prefix = CitizenCardNoGeneratorUtil.getCardNoPrefix(
		// cardProductCode, 。);
		// System.out.println("*****卡面号前缀***********" + prefix);
		// cd.setCitizenCardNo(generatorCardNo(prefix));
		cd.setPhotoId("photoId");// 拍照的话，设置
		cdm.insert(cd);
		System.out.println("卡数据表的Id" + cd.getCardDataId());

		
		// 卡控制表
		CardControl cc = new CardControl();
		cc.setCardDataId(cd.getCardDataId());
		cc.setApplyDate(ccc.getTime());
		// cc.setCardDate(cardDate);//制卡日期
		cc.setCardPosition(CardContants.CARD_POSITION_COUNTER_EMPLOYEE);// 位置在柜员呢
		cc.setCardStatus(CardContants.CARD_STATE_DISABLED);// 卡状态未启用
		cc.setCrtDate(new Date());
		cc.setCrtOperator(activeUser.getUserNo().toString());
		cc.setLastDate(new Date());
		cc.setLastOperator(activeUser.getUserNo().toString());
		// cc.setClaimStatus(CardContants.CARD_STATUS_APPLY);
		cc.setBlacklistFlag(CardContants.BLACKLIST_FLAG_NORMAL);
		cc.setDmgFlag(CardContants.CARD_UNDAMAGED);// 卡损坏状况
													// :未损坏-----0未损坏，1非人为损坏，2人为损坏
		// cc.setLogoutDate(logoutDate);//注销日期
		// cc.setLogoutReason(logoutReason);//注销原因

		// cc.setReleaseDate(ccc.getTime());//发卡日期
		cc.setRemark("这是备注");
		cc.setApplyType(CardContants.APPLY_TYPE_FIRST);
		cc.setClaimStatus(CardContants.CLAIM_STATUS_APPLY);

		ccm.insert(cc);

		// 凭证表
		Cert ce = new Cert();
		ce.setCertNo(SequenceNumberUtil.generatorCertNo());
		// ce.setAgentName(agentName);
		// ce.setAgentPaperNo(agentPaperNo);
		// ce.setAgentPapertype(agentPapertype);
		ce.setBranch(activeUser.getBranchName());// 网点名称
		ce.setBranchNo(activeUser.getBranchNo());// 网点编号
		// ce.setBusinessNo(businessNo);//业务流水号
		ce.setCardControlId(cc.getCardControlId());
		ce.setCertType(CardContants.SINGLE_APPLICATION);// 凭证类型 1 单笔申请 2 批量申请 3
														// 出库配送 4 单笔发卡 5 批量发卡
		ce.setCardpCode(cardProductCode);// 卡产品代码
		ce.setCardTypecode(cpd.getCardTypeCode());// 卡类型代码 1.标准卡 2.记名衍生卡
													// 3.非记名衍生卡
		// ce.setCorpCode(corpCode);//单位编号id
		ce.setCorpName(p.getCorpName());// 单位名称
		ce.setCrtDate(new Date());
		ce.setCrtOperator(activeUser.getUserNo().toString());
		String str = "{\"title\":\""+"单笔申请凭证"+"\",\"type\":\""+"applyRegister"+"\",\"certNo\":\""+ce.getCertNo()
		+"\",\"busType\":\""+CardContants.getCertTypeNameByCode(ce.getCertType())+"\",\"cardType\":\""+cpt.queryCardPhysicsTypeByCode(cardPhysicalType).getCardTypeName()
		+"\",\"cardpName\":\""+cpd.getCardpName()+"\",\"net\":\""+activeUser.getBranchName()+"\",\"operator\":\""
		+activeUser.getUserNo().toString()+"\",\"date\":\""+DateFormatUtils.format(new Date(), "yyyy-MM-dd")+"\"}";
		ce.setData(str);
		//ce.setData("打印凭证数据 ");// 打印凭证数据
		ce.setLastDate(new Date());
		ce.setLastOperator(activeUser.getUserNo().toString());
		ce.setName(p.getCustomerName());// 持卡人姓名
		ce.setPaperNo(p.getPaperNo());
		ce.setPaperType(p.getPaperType());
		ce.setPrintCount(1);// 打印次数
		ce.setTransCode("单笔申请");//交易代码
		ce.setBranch(activeUser.getBranchName());
		ce.setBranchNo(activeUser.getBranchNo());
		

		// 业务流水表

		Business b = new Business();
		b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
		// b.setAgentName(agentName);//代理人姓名
		// b.setAgentPaperNo(agentPaperNo);//代理人证件号码
		// b.setAgentPapertype(agentPapertype);//代理人证件类型
		// b.setAgentPhone(agentPhone);// 代理人联系电话
		// b.setBatchNo(batchNo);//批次号
		b.setBusiNum(1);// 业务数量
		b.setCardControlId(cc.getCardControlId());// 卡控制号
		b.setCardpCode(cardProductCode);// 卡产品
		b.setCertNo(ce.getCertNo());// 凭证编号
		// b.setCorpNo(corpNo);//单位编号 批量办理时使用
		b.setCustomerNo(p.getCustomerNo());// 客户编号
		b.setRemark("当前业务流水");// 备注
		// b.setRptDate(rptDate);//轧帐日期
		// b.setRptFlag(rptFlag);//轧帐标识
		b.setTellerNo(activeUser.getUserNo().toString());// 柜员号
		b.setTransAuthId("业务授权人编号001");// 业务授权人编号
		b.setTransAuthName("业务授权人姓名-赵铁柱");// 业务授权人姓名
		// b.setTransCode(transCode);//交易代码
		// b.setTransDate(transDate);//交易日期
		b.setSeqStatus(CardContants.LSZT_NORMAL);// 0.临时1.正常 2.撤销
													// 3.冲正默认为1正常，目前暂时没有使用2撤销和3冲正的情况

		bm.insert(b);

		ce.setBusinessNo(b.getBusinessNo());
		cem.insert(ce);

		// 卡过程信息
		CardManage cme = new CardManage();
		cme.setProcessId(UUID.randomUUID().toString().replace("-", ""));
		cme.setApplyBranch(activeUser.getBranchName());
		cme.setApplyBranchNo(activeUser.getBranchNo());
		cme.setApplyDate(new Date());// 发生的日期
		cme.setApplyTellerNo(activeUser.getUserNo().toString());
		cme.setBusinessNo(b.getBusinessNo());
		cme.setCertNo(ce.getCertNo());
		// cme.setProcessCode(CardContants.CARD_PROC_APPLY);
		 cme.setProcessName("单笔申请");
		// cme.setCitizenCardNo(cd.getCitizenCardNo());
		cme.setCardPosition(CardContants.CARD_POSITION_CENTRAL_STOREROOM);// 中心库房
		cme.setCardpCode(cardProductCode);// 卡产品
		cme.setCardTypecode(cpd.getCardTypeCode());// 卡类型
		cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
		cme.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
		cmm.insert(cme);

		cc.setCurrProcId(cme.getProcessId());

		ccm.updateCardControl(cc);
		
		VoucherVo vv = new VoucherVo();
		vv.setCertNo(ce.getCertNo());
		vv.setBusinessTypeName(CardContants.getCertTypeNameByCode(ce.getCertType()));
		vv.setCardType(cpt.queryCardPhysicsTypeByCode(cardPhysicalType).getCardTypeName());
		vv.setCardpName(cpdm.queryCardCode(cardProductCode).getCardpName());
		// vv.setNewCitizenCardNo(scv.getNewCitizenCardNo());
		vv.setExpectCardDate(ccc.getTime());
		vv.setDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
		vv.setOperator(String.valueOf(activeUser.getUserNo()));
		logger.debug("operator==>" + vv.getOperator());
		vv.setNet(activeUser.getBranchName());
		ResultStatus resultStatus = new ResultStatus();
		resultStatus.setCode(HttpContants.RETURN_SUCCESS);
		resultStatus.setMessage("返回成功");
		rv.setResultStatus(resultStatus);
		rv.setServiceObject(vv);
		return rv;
		
	}

	/**
	 * 单笔申请的附件保存（有效证件，采集单）
	 * 
	 * @throws Exception
	 */
	public ResultVo saveSingleEnclosure(List<CollAttach> list){
		ResultVo vo = new ResultVo();
		ResultStatus resultStatus = new ResultStatus();
		if(list.size()>0){
			
			cam.batchInsert(list);
			resultStatus.setCode(HttpContants.RETURN_SUCCESS);
			resultStatus.setMessage("保存成功");
			vo.setResultStatus(resultStatus);
		}
		return vo;
	}

	/**
	 * 根据证件类型和证件号码获取个人资料（基本信息+照片）
	 * 
	 * @param paperType
	 *            证件类型
	 * @param paperNo
	 *            证件号码
	 * @return 个人信息
	 */
	public ResultVo queryPersonalAndPhotoByPaperNo(String paperType, String paperNo) {
		ResultVo rv = new ResultVo();
		ResultStatus rs = new ResultStatus();
		rs.setCode(HttpContants.RETURN_SUCCESS);
		rs.setMessage("返回成功");
		rv.setResultStatus(rs);
		if (StringUtils.isEmpty(paperType) || StringUtils.isEmpty(paperNo)) {
			rs.setCode(ErrorCode.OBJECT_IS_NULL);
			rs.setMessage("证件类型或证件号码为空");
			rv.setResultStatus(rs);
			return rv;
		}
		Personal p = pm.queryPersonalByPaperNo(paperType, paperNo);
		Photo ph = phm.queryPhotoByPaperNo(paperType, paperNo);
		p.setPhotoPath(ph.getPhoto());

		rv.setResultStatus(rs);
		rv.setServiceObject(p);
		return rv;
	}

	/**
	 * 测试用的
	 * 
	 * @throws ApplicationException
	 * @throws ParseException
	 * 
	 */
	@Override
	public void excel(String[] paths) throws Exception {
		
	}
	
	//循环生成批次卡号
//	List<String> list = new ArrayList<>();
	@Override
	public List<String> generatorCardNo_list(String prefix,List<String> list,int size) throws Exception {
		
		logger.info("generatorCardNo########start()");
//		
		int valid = 0; //初始化

		String dd = list.get(list.size()-1);
		String endNo = "";
		if (StringUtils.isNotEmpty(dd)) {
			endNo = dd.substring(5);// 最新一条数据的市民卡号后7位
		} else {
			throw new ApplicationException(ErrorCode.OBJECT_IS_NULL, "CitizenCardNo is null !!!");
		}

		Integer newNo = Integer.parseInt(endNo) + 1;// 生成 后7位+1
		
		String gg = CitizenCardNoGeneratorUtil.generatorSeq(newNo.toString(), 7);
		

		valid = CardUtil.calcLuhn(prefix + gg);
		String newCardNo = prefix + valid + gg;// 组合卡面号
		if (CardUtil.verifyCardNo(newCardNo)) {
			// 20180131 惠国磊 以下一行 增加
			logger.info("generatorCardNo########end()");
			list.add(newCardNo);
			if(list.size() == size){
				return list;
			}else{
				return generatorCardNo_list(prefix, list, size);
			}
			
		}

		else {
			throw new ApplicationException(ErrorCode.DATA_ILLEGALITY, "卡面号不合法");
		}

	}

	@Override
	public String generatorCardNo(String prefix,CardData cd) throws Exception {
		int valid = 0;
		if (cd == null) {
			valid = CardUtil.calcLuhn(prefix+"0000001");
			return prefix + valid + "0000001";
		}
		String dd = cd.getCitizenCardNo();
		String endNo = "";
		if (StringUtils.isNotEmpty(dd)) {
			endNo = cd.getCitizenCardNo().substring(5);// 最新一条数据的市民卡号后7位
		} else {
			throw new ApplicationException(ErrorCode.OBJECT_IS_NULL, "CitizenCardNo is null !!!");
		}
		logger.error("***************************上一条卡面号*****：[{}]", cd.getCitizenCardNo());

		Integer newNo = Integer.parseInt(endNo) + 1;// 生成 后7位+1
		String gg = CitizenCardNoGeneratorUtil.generatorSeq(String.valueOf(newNo), 7);
		

		valid = CardUtil.calcLuhn(prefix + gg);
		String newCardNo = prefix + valid + gg;// 组合卡面号
		if (CardUtil.verifyCardNo(newCardNo)) {
			// 20180131 惠国磊 以下一行 增加
			logger.info("generatorCardNo########end()");
			return newCardNo;
		}

		else {
			throw new ApplicationException(ErrorCode.DATA_ILLEGALITY, "卡面号不合法");
		}

	}

	/**
	 * 卡面号的生成
	 */
	@Override
	public String generatorCardNo(String prefix,String cardPCode) throws Exception {
		// 20180131 惠国磊 以下一行 增加
		logger.info("generatorCardNo########start()");
		CardData cd = cdm.queryNewestObject(cardPCode);
		
		return generatorCardNo(prefix, cd);

	}

	@Override
	public ResultVo queryPersonalByPaperNoAndPaperType(String paperType, String paperNo) {
		ResultVo rv = new ResultVo();
		ResultStatus rs = new ResultStatus();
		rs.setCode(HttpContants.RETURN_SUCCESS);
		rs.setMessage("返回成功");
		rv.setResultStatus(rs);
		if (StringUtils.isEmpty(paperType) || StringUtils.isEmpty(paperNo)) {
			rs.setCode(ErrorCode.OBJECT_IS_NULL);
			rs.setMessage("证件类型或证件号码为空");
			rv.setResultStatus(rs);
			return rv;
		}
		rv.setResultStatus(rs);
		Personal p = pm.queryPersonalByPaperNo(paperType, paperNo);
		if( p == null){
			rs.setCode(ErrorCode.PERSON_NOT_EXIST);
			rs.setMessage("查无此人");
			return rv;
		}
		rv.setServiceObject(p);
		return rv;

	}

	@Override
	public DwzPage<Other> queryApplyBatchListByPage(int currentPage, int pageSize,String root) {
		/* 列表信息，批次号，状态 */
		List<Other> list = new ArrayList<>();
		/* 未导入的文件的批量申请号 数组列表 */
		List<String> ll = Excel.unImportApplyNos(root);
		logger.debug("未导入的批次号==>" + ll.toString());
		
		if(ll.size() == 0){
			
		}else{
			for (String applyBatchNo : ll) {

				// 检查是否存在该批次号
				int count = ptm.checkExistApplyBatchNoByApplyBatchNo(applyBatchNo);
				try {
					applyBatchNo = java.net.URLDecoder.decode(applyBatchNo, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					String msg="批次号解码失败";
					logger.error(msg);
					throw new SystemException(SystemException.UnsupportedEncodingException, msg);

				}
				if (count > 0) {
					// 未导入的批次号
					Other o = new Other(applyBatchNo, false);
					list.add(o);
				} else {
					Other o = new Other(applyBatchNo, true);
					list.add(o);
				}

			}
		}
		

		DwzPage<Other> dp = new DwzPage<Other>(currentPage, pageSize, list.size());
		dp.setList(list);

		return dp;
	}

	@Override
	public ResultVo query(String paperType, String paperNo, String condition) {
		ResultVo rv = new ResultVo();
		ResultStatus rs = new ResultStatus();
		rs.setCode(HttpContants.RETURN_SUCCESS);
		rs.setMessage("返回成功");
		rv.setResultStatus(rs);

		if (StringUtils.isEmpty(paperType) || StringUtils.isEmpty(paperNo)) {
			rs.setCode(ErrorCode.OBJECT_IS_NULL);
			rs.setMessage("证件类型或证件号码不能为空");
			rv.setResultStatus(rs);
			return rv;
		}

		QueryCardDataVo qv = new QueryCardDataVo();
		qv.setPaperNo(paperNo);
		qv.setPaperType(paperType);

		List<ApplyScheduleVo> list = new ArrayList<>();

		if ("1".equals(condition)) {// 待申请
			qv.setCardStatus1(CardContants.CARD_STATE_CANCELLATION_NO_CARD);
			qv.setCardStatus2(CardContants.CARD_STATE_CANCELLATION_HAS_CARD);

			List<CardData> lc = cdm.queryCardDataByStatus(qv);// 该用户没有被注销的卡

			List<CardProdunctDefinition> lcp = cpdm.queryAvailableCardProdunctDefinitionByInternet(CardContants.CARD_TYPE_REGISTERED, CardContants.CARD_PROPERTY_COMMON,CardContants.STATUS_ENABLE);

			
			Iterator<CardProdunctDefinition> it = lcp.iterator();
			while (it.hasNext()) {
				CardProdunctDefinition cpd = it.next();
				boolean b = false;
				for (CardData cd : lc) {
					if (cd.getCardpCode().equals(cpd.getCardpCode())) {
						it.remove();
						break;
					}
				}
				continue;

			}

			for (CardProdunctDefinition cpd : lcp) {// 未申请的卡
				ApplyScheduleVo v = new ApplyScheduleVo();
				v.setSchedule("1");
				v.setCardPName(cpdm.queryCardPCode(cpd.getCardpCode()).getCardpName());
				v.setScheduleName("未申请");

				list.add(v);
			}
		} else if ("2".equals(condition)) {// 已经申请
			List<CardData> lc1 = cdm.queryCardDataByPaperNoAndCardStatus(paperType, paperNo, null,
					CardContants.CARD_STATE_DISABLED);
			for (CardData cd : lc1) {
				ApplyScheduleVo v = new ApplyScheduleVo();
				CardControl cc = ccm.queryCardControlByCardDataId(cd.getCardDataId());

				v.setCardPName(cpdm.queryCardPCode(cd.getCardpCode()).getCardpName());
				v.setSchedule("2");
				v.setScheduleName("已申请");
				v.setDate(cc.getLastDate());
				if (CardContants.CLAIM_STATUS_APPLY.equals(cc.getClaimStatus())) {// 普通申请
					v.setBussinessName("普通申请类业务");
					Cert c = cem.queryCertByPersonal(cc.getCardControlId(), paperType, paperNo,
							CardContants.SINGLE_APPLICATION, cd.getCardpCode());
					v.setBussinessNo(c.getCertNo());
				} else if (CardContants.CLAIM_STATUS_SUPPLEMENTARY_CARD_APPLICATION.equals(cc.getClaimStatus())) {// 补卡申请
					v.setBussinessName("补卡申请类业务");
					Cert c = cem.queryCertByPersonal(cc.getCardControlId(), paperType, paperNo,
							CardContants.CARD_ISSUING_APPLY, cd.getCardpCode());
					v.setBussinessNo(c.getCertNo());
					v.setChcOriCitizenNo(cd.getChcOriCitizenNo());
				}
				list.add(v);
			}
		} else if ("3".equals(condition)) {// 已经领取
			qv.setCardStatus1(CardContants.CARD_STATE_NORMAL);
			qv.setCardStatus2(CardContants.CARD_STATE_OFFICIAL_LOSS);
			qv.setCardStatus3(CardContants.CARD_STATE_ORAL_LOSS);

			List<CardData> lc2 = cdm.queryCardDataByPaperNoAndNormal(qv);
			for (CardData cd : lc2) {
				ApplyScheduleVo v = new ApplyScheduleVo();
				CardControl cc = ccm.queryCardControlByCardDataId(cd.getCardDataId());
				v.setCitizenCardNo(cd.getCitizenCardNo());
				v.setBussinessName("申领类业务");
				Cert c = cem.queryCertByPersonal(cc.getCardControlId(), paperType, paperNo, CardContants.SINGLE_CARD,
						cd.getCardpCode());
				v.setBussinessNo(c.getCertNo());
				v.setCardPName(cpdm.queryCardPCode(cd.getCardpCode()).getCardpName());
				v.setDate(cc.getLastDate());
				v.setSchedule("3");
				v.setScheduleName("已领取");
				list.add(v);
			}

		}

		ResultObject ro = new ResultObject();

		ro.setItems(list);

		rv.setServiceObject(ro);

		return rv;
	}

	@Override
	public ResultVo queryApplySchedule(String paperNo, String paperType, String condition) {
		ResultVo rv = new ResultVo();
		ResultStatus rs = new ResultStatus();
		rs.setCode(HttpContants.RETURN_SUCCESS);
		rs.setMessage("返回成功");
		rv.setResultStatus(rs);
		if (StringUtils.isEmpty(paperType) || StringUtils.isEmpty(paperNo)) {
			rs.setCode(ErrorCode.OBJECT_IS_NULL);
			rs.setMessage("证件类型或证件号码不能为空");
			rv.setResultStatus(rs);
			return rv;
		}
		List<ApplyScheduleVo> ll = new ArrayList<>();

		if (StringUtils.isEmpty(condition) || "0".equals(condition)) {
			// 全部
			ResultVo rv1 = query(paperType, paperNo, "1");
			if (rv1.getResultStatus().getCode() == HttpContants.RETURN_SUCCESS) {
				ResultObject ro = (ResultObject) rv1.getServiceObject();
				List<ApplyScheduleVo> l1 = (List<ApplyScheduleVo>) ro.getItems();
				ll.addAll(l1);
			}

			ResultVo rv2 = query(paperType, paperNo, "2");
			if (rv2.getResultStatus().getCode() == HttpContants.RETURN_SUCCESS) {
				ResultObject ro = (ResultObject) rv2.getServiceObject();
				List<ApplyScheduleVo> l1 = (List<ApplyScheduleVo>) ro.getItems();
				ll.addAll(l1);
			}

			ResultVo rv3 = query(paperType, paperNo, "3");
			if (rv3.getResultStatus().getCode() == HttpContants.RETURN_SUCCESS) {
				ResultObject ro = (ResultObject) rv3.getServiceObject();
				List<ApplyScheduleVo> l1 = (List<ApplyScheduleVo>) ro.getItems();
				ll.addAll(l1);
			}

		} else {
			ResultVo rv2 = query(paperType, paperNo, condition);
			if (rv2.getResultStatus().getCode() == HttpContants.RETURN_SUCCESS) {
				ResultObject ro = (ResultObject) rv2.getServiceObject();
				List<ApplyScheduleVo> l1 = (List<ApplyScheduleVo>) ro.getItems();
				ll.addAll(l1);
			}
		}
		ResultObject ro1 = new ResultObject();
		ro1.setItems(ll);
		rv.setServiceObject(ro1);

		return rv;
	}

	@Override
	public ResultVo generateCollectionNo() {
		ResultVo rv = new ResultVo();
		ResultStatus rs = new ResultStatus();
		rs.setCode(HttpContants.RETURN_SUCCESS);
		rs.setMessage("返回成功");
		rv.setResultStatus(rs);
		Collection c = colm.queryMaxCollectionNo();
		String collectionNo = "";
		if (c == null) {
			collectionNo = CardContants.SINGLE_APPLY_COLLECTION_NO_PREFIX + "0000001";
		} else {
			String maxCollectionNo = c.getCollectionNo();
			String end = maxCollectionNo.substring(10);
			Integer newSeq = Integer.valueOf(end) + 1;
			String newEnd = CitizenCardNoGeneratorUtil.generatorSeq(String.valueOf(newSeq), 7);
			collectionNo = CardContants.SINGLE_APPLY_COLLECTION_NO_PREFIX + newEnd;
		}

		ResultObject ro = new ResultObject();
		ro.setStr(collectionNo);
		rv.setServiceObject(ro);
		return rv;
	}

	@Override
	public ResultVo saveCollection(Personal p,String cardCode) {
		
		
		ResultVo rv = new ResultVo();
		ResultStatus rs = new ResultStatus();
		Date now = new Date();
		Calendar ccc = Calendar.getInstance();
		ccc.setTime(now);
		ccc.add(Calendar.DAY_OF_MONTH, bpm.queryBusiParamByCardPCode(cardCode).getReleaseDays());// 今天+n天===预计领卡日期
		
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}

		if (activeUser == null) {
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		// 采集表
		Collection c = new Collection();
		c.setApplyDate(ccc.getTime());// 申领日期
		c.setCollBranchName(activeUser.getBranchName());// 采集网点名称
		c.setCollBranchNo(activeUser.getBranchNo());// 采集网点编号
		ResultVo r = generateCollectionNo();
		if(r.getResultStatus().getCode() == HttpContants.RETURN_SUCCESS){
			ResultObject o = (ResultObject) r.getServiceObject();
			c.setCollectionNo(o.getStr());// 采集单编号
		}else{
			
			rs.setCode(ErrorCode.OBJECT_IS_NULL);
			rs.setMessage("采集单编号生成失败");
			rv.setResultStatus(rs);
			return rv;
		}
		c.setCustomerName(p.getCustomerName());
		c.setPaperNo(p.getPaperNo());
		c.setPaperType(cfm.queryCertificateByName(p.getPaperType()).getCertificateType());
		c.setCrtDate(now);// 创建日期
		c.setCrtOperator(activeUser.getUserNo().toString());// 创建柜员号
//		c.setCustomerNo(p.getCustomerNo());// 客户编号,提交个人信息时 在更新此字段
		c.setDataOrigin(CardContants.DATA_ORIGIN_INPUT_BY_HAND);// 数据来源 1读取二代身份证
																// 2手工录入 ---参考
																// cardcontants.class
		c.setIsPhoto(p.getOtherInfo01());// 是否拍照 0否 1是 默认为否，即0否
		c.setLastDate(new Date());// 最后修改日期
		c.setIsUrgent("0");// 是否加急 0.不加急 1.加急 默认为0不加急
		c.setLastOperator(activeUser.getUserNo().toString());// 最后修改柜员号
		colm.insert(c);
		rs.setCode(HttpContants.RETURN_SUCCESS);
		rs.setMessage("保存采集单成功");
		rv.setResultStatus(rs);
		ResultObject ro = new ResultObject();
		ro.setStr(c.getCollectionId());
		rv.setServiceObject(c);
	logger.debug("生成采集单编号："+c.getCollectionNo());
		return rv;
	}

	@Override
	public ResultVo uploadImageByApplicationSingle(String imageBasecode64, String absoluteRoot, String path, String photoName,String photoType,String paperType) {
		logger.debug("进入拍照service");
		byte[] b  = Base64.decodeBase64(imageBasecode64);
		boolean f=IMG.uploadPhoto(absoluteRoot + path, photoName+photoType, b);
		ActiveUser activeUser=(ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		Photo photo=phm.queryPhotoByPaperNo(paperType, photoName);
		Date now=new Date();
		ResultVo vo=new ResultVo();
		if(f){
			if(photo==null){
				photo=new Photo();
				photo.setPaperNo(photoName);
				photo.setPaperType(paperType);
				photo.setPhotoSource("2");
				photo.setPhotoType("3");
				photo.setRemark("单笔申请拍照");
				photo.setPhoto(path+photoName);
				photo.setCrtDate(now);
				photo.setCrtOperator(String.valueOf(activeUser.getUserNo()));
				photo.setLastDate(now);
				photo.setLastOperator(String.valueOf(activeUser.getUserNo()));
				phm.savePhoto(photo);
				logger.debug("保存photo");
			}else{
				photo.setPhotoSource("2");
				photo.setPhotoType("3");
				photo.setRemark("单笔申请拍照");
				photo.setPhoto(path+photoName);
				photo.setLastDate(now);
				photo.setLastOperator(String.valueOf(activeUser.getUserNo()));
				phm.updatePhoto(photo);
				logger.debug("更新photo");
			}
			
			vo.setResultStatus(new ResultStatus(HttpContants.RETURN_SUCCESS,"照片上传成功"));
			vo.setServiceObject(photo);
		}else{
			vo.setResultStatus(new ResultStatus(300,"照片上传失败"));
		}
		return vo;
	}

	

	@Override
	public List<String> queryAllApplyNos() {
		
		return bcm.queryBatchApplyNos();
	}

	
	
	@Override
	public boolean modifyPersonal(Personal p) {
		int a = pm.updateByCustomerNO(p);
		if(a>0){
			return true;
		}else{
			return false;
		}
		
	}

	@Override
	public List<Personal> queryPersonal(String paperType, String paperNo, String mobile) throws ApplicationException {
		if(StringUtils.isEmpty(paperNo) && StringUtils.isEmpty(mobile)){
			throw new ApplicationException(ErrorCode.PAPERNO_IPHOTO_ISNULL, "证件号码或者手机号码不能为空");
		}
		
		return pm.queryPersonalByCondition(paperType, paperNo, mobile);
	}

	@Override
	public boolean checkExistPerson(String paperType, String paperNo,String customerNo) throws ApplicationException {
		if(StringUtils.isEmpty(paperNo) && StringUtils.isEmpty(paperType)){
			throw new ApplicationException(ErrorCode.PAPERNO_IPHOTO_ISNULL, "证件类型或者证件号码不能为空");
		}
		
		if(paperType.equals("00")||paperType.equals("01")){
			if(!CommonUtil.isIDNumber(paperNo)){
				throw new ApplicationException(ErrorCode.DATA_FORMAT_ERROR, "证件号码格式错误");
			}
		}
		
		int num = pm.queryPersonalCountByPaperNo(paperType, paperNo);
		if(num == 1){
			Personal p = pm.queryPersonalByCustomerNo(customerNo);
			if(p.getPaperType().equals(paperType) && p.getPaperNo().equals(paperNo)){
				return false;
			}
			return true;
		}else if(num>1){
			return true;
		}
		return false;
	}

	
	@Override
	public VoucherVo charge(ShowChargeVo scv) throws ApplicationException {
		ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		
		VoucherVo vo = new VoucherVo();
		Date now = new Date();
		
		
		
		
		
		// 凭证表
				Cert ce = new Cert();
				ce.setCertNo(SequenceNumberUtil.generatorCertNo());
				// ce.setAgentName(agentName);
				// ce.setAgentPaperNo(agentPaperNo);
				// ce.setAgentPapertype(agentPapertype);
				ce.setBranch(activeUser.getBranchName());// 网点名称
				ce.setBranchNo(activeUser.getBranchNo());// 网点编号
				// ce.setBusinessNo(businessNo);//业务流水号
//				ce.setCardControlId(cc.getCardControlId());
				ce.setCertType(CardContants.BATCH_APPLICATION);// 凭证类型 1 单笔申请 2 批量申请 3
																// 出库配送 4 单笔发卡 5 批量发卡
				ce.setCardpCode(scv.getCardProductCode());// 卡产品代码
				ce.setCardTypecode(CardContants.CARD_TYPE_REGISTERED);// 卡类型代码 1.标准卡 2.记名衍生卡
															// 3.非记名衍生卡
				// ce.setCorpCode(corpCode);//单位编号id
				ce.setCorpName(scv.getCorpName());// 单位名称
				ce.setCrtDate(now);
				ce.setCrtOperator(activeUser.getUserNo().toString());
				ce.setData("批量申请-收费 ");// 打印凭证数据
				ce.setLastDate(new Date());
				ce.setLastOperator(activeUser.getUserNo().toString());
//				ce.setName(p.getCustomerName());// 持卡人姓名
//				ce.setPaperNo(p.getPaperNo());
//				ce.setPaperType(p.getPaperType());
				ce.setPrintCount(1);// 打印次数
				ce.setTransCode("批量申请-收费 ");//交易代码
				ce.setBranch(activeUser.getBranchName());
				ce.setBranchNo(activeUser.getBranchNo());
				

				// 业务流水表

				Business b = new Business();
				b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
				// b.setAgentName(agentName);//代理人姓名
				// b.setAgentPaperNo(agentPaperNo);//代理人证件号码
				// b.setAgentPapertype(agentPapertype);//代理人证件类型
				// b.setAgentPhone(agentPhone);// 代理人联系电话
				 b.setBatchNo(scv.getApplyBatchNo());//批次号
				b.setBusiNum(scv.getNum());// 业务数量
//				b.setCardControlId(cc.getCardControlId());// 卡控制号
				b.setCardpCode(scv.getCardProductCode());// 卡产品
				b.setCertNo(ce.getCertNo());// 凭证编号
//				 b.setCorpNo(corpNo);//单位编号 批量办理时使用
//				b.setCustomerNo(p.getCustomerNo());// 客户编号
				b.setRemark("批量申请-收费");// 备注
				// b.setRptDate(rptDate);//轧帐日期
				// b.setRptFlag(rptFlag);//轧帐标识
				b.setTellerNo(activeUser.getUserNo().toString());// 柜员号
//				b.setTransAuthId("业务授权人编号001");// 业务授权人编号
//				b.setTransAuthName("业务授权人姓名-赵铁柱");// 业务授权人姓名
				// b.setTransCode(transCode);//交易代码
				// b.setTransDate(transDate);//交易/日期
				b.setSeqStatus(CardContants.LSZT_NORMAL);// 0.临时1.正常 2.撤销
															// 3.冲正默认为1正常，目前暂时没有使用2撤销和3冲正的情况

				bm.insert(b);

				ce.setBusinessNo(b.getBusinessNo());
				cem.insert(ce);
		
				FeeRulesVo fv= new FeeRulesVo();
				fv.setCardpCode(scv.getCardProductCode());
				fv.setFeeType(AccountContants.FEE_TYPE_NOMINAL_FEE);
				fv.setNow(now);
				
				
				// 当日交易明细
				TxnDtl td = new TxnDtl();
//				td. setCrdNo("") ;
//				td. setCardSeqNo(""); 
//				td. setCrdUniqueNo("");
//				td. setCitizenCardNo(scv.getNewCitizenCardNo());
//				td. setSubaccountNo(String subaccountNo);
				td. setIssCityCd(CardContants.CITY_CODE);		
				td. setTxnCityCd(CardContants.CITY_CODE) ;
//				td. setCrdIndustCd(String crdIndustCd);//卡行业代码
//				td. setAppFlag(bv.getAppFlag());
//				td. setCrdPhysTp(String crdPhysTp) ;//卡物理类型 		  
//				td. setCtSeq(String ctSeq);//中心流水号 			   
//				td. setCtDt(Date ctDt) ;//中心时间
				td. setCashFlag(AccountContants.CASH_FLAG_COLLECT); //现金收付标志 0.无,1.收取 2.支出,3.收支
//				td. setTxnTp(bv.getCrdTxnType());//	卡交易类型
				td. setTxnDt(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));			   
//				td. setTxnBalBef(totalBalance) ;//账户交易前余额		 
//				td. setTxnBalAft(cardWallet.getTotalBalance());	
				BigDecimal bb = new BigDecimal(scv.getFee());
			    	td.setTxnAmt(bb) ;	//交易金额
				    td.setRealTxnAmt(bb);//实际交易金额
//				td. setCrdBalBef(bv.getCrdBalBef()) ;//卡交易前 余额
//				td. setCrdBalAft(bv.getCrdBalAft()) ;
//				td. setSetDt(Date setDt);//结算日期			   
				td. setFeeTp(AccountContants.FEE_TYPE_NOMINAL_FEE);//费用类型  0.本金 1:工本费 2.交易手续费 3:租金4:押金			    
				td. setAcceptTp(AccountContants.ACCEPTANCE_TYPE_NET);//受理类型 表示终端的归属，由上传的终端代码决定：01-网点 06-商户
			    td. setAcceptCusNo(activeUser.getBranchNo()) ;//受理商户/网点编号			  
//				td. setTermNo("");//终端代码			    
//				td. setTermSeq(String termSeq) ;//终端流水号			   
//			    td. setSamNo(bv.getSamNo());//			  
//				td. setSamSeq(String samSeq) ;			    
//				td. setTxnFileName("");//交易文件名称
//				td. setPkgRecOrd(Integer pkgRecOrd) ;//所属数据包记录序号 
//			    td. setDivFactor(bv.getDivFactor());
//			    td. setTxnTac(bv.getTxnTac());
//				td. setTxnCharcFld(String txnCharcFld) ;//交易个性域
			    td. setTxnTstFlg(AccountContants.TRANSACTION_TEST_FLAG_COMMON) ;//交易测试标志 "0"-普通; "1"-测试			   
//				td. setErrCode(String errCode);//错误代码 记录级错误			    
//				td. setTxnAdjFlg(String txnAdjFlg);//交易流水标志 "00" 正常 "41" 撤销			   
//				td. setAdjCtSeq(String adjCtSeq) ;//关联中心流水号			    
//				td. setAdjCtDt(Date adjCtDt);//关联中心时间
//				td. setTxnMac1(String txnMac1) ;
//				td. setTxnMac2(String txnMac2);			  
//				td. setAdjSetDt(Date adjSetDt) ;//关联结算日期			   
//				td. setLastTxnCnt(cardWallet.getTotalReloadCnt()) ;//上一次交易卡计数器			   
//				td. setLastTxnDt(Date lastTxnDt) ;//上一次交易时间			 
//				td. setLastTxnAmt(BigDecimal lastTxnAmt) ;//上一次交易金额			   
//				td. setCurrCount(Integer currCount);//当前计数器值 		   
			    td. setWarrantid(ce.getCertNo()) ;//凭证号
//				td. setOutWarrantid(String outWarrantid);//外部凭证号			   
			    td. setOprNo(activeUser.getUserNo().toString());//操作员编号/终端操作员编号 			  
//				td. setLocalTxnSeq(String localTxnSeq);//本地流水号			    
//			    td. setTxnAttr(AccountContants.TXNTP_RECHARGE) ;//交易性质 			   
//				td. setStationId(String stationId) ;//采集点编号
//				td. setPosCarrId(String posCarrId);//POS机载体编号
			    td. setCrdCityCd(CardContants.CITY_CODE);//卡城市代码
			    td. setCardType(CardContants.CARD_TYPE_REGISTERED);
			    td. setRsvdFlags(AccountContants.TXNTP_COST);	//预留标志组		   
//				td. setRsvdFld(String rsvdFld);//保留字段
//				td. setFileGenDate(Date fileGenDate) ;//文件生成日期 	   
//			    td.setTxnType(AccountContants.TRADE_TYPE_BUS) ;//终端交易类型  
			    td.setTxnDate(new SimpleDateFormat("yyyyMMdd").format(now)) ;	//交易日期		   
//				td.setOutEntityno(String outEntityno);//外部实体编号
			    td. setBusinessNo(b.getBusinessNo());//
			    td. setPaymentType(AccountContants.PAYMENT_TYPE_CASH);//支付方式  0 现金 1 兑换券  默认为0
			    td.setPaymentTypeExt(AccountContants.STATUS_INVALID);//支付方式是否扩展 0 否1 是  默认为0
			    tdm.insert(td);
				
				// 交易明细流水表
				TransGlide tg = new TransGlide();
				tg.setAcceptTp(AccountContants.ACCEPTANCE_TYPE_NET);// 受理类型
				//tg.setAccountType(bv.getWalletType());// 账户类型
				tg.setAllowReturn(AccountContants.STATUS_INVALID);//不可退费
				//tg.setAppFlag(bv.getAppFlag());// 应用标识
				//tg.setAppType(bv.getAppType());// 应用类型
				tg.setBranchNo(activeUser.getBranchNo());
				tg.setBusinessNo(b.getBusinessNo());//业务流水号
//				tg.setCitizenCardNo(scv.getNewCitizenCardNo());// 卡市民卡号
				tg.setCashFlag(AccountContants.CASH_FLAG_COLLECT);// 现金收付标志
					tg.setFeeRuleId(scv.getFeeRuleId());//卡费用规则ID
					tg.setFeeRulesId(scv.getFeeRulesId());//卡费用细则ID
				tg.setFeeTp(AccountContants.FEE_TYPE_NOMINAL_FEE);// 费用类型
				// tg.setIsReturned(AccountContants.STATUS_VALID);//是否已退费
				tg.setOprNo(activeUser.getUserNo().toString());
				tg.setPaymentType(AccountContants.PAYMENT_TYPE_CASH);// 现金

				tg.setPaymentTypeExt(AccountContants.STATUS_INVALID);
				// tg.setRptDate(rptDate);//轧帐日期
				tg.setRptFlag(AccountContants.RPT_FLAG_NO);// 轧帐标识 0未过账
				// tg.setSubaccountNo(subaccountNo);//网点子账号
				// tg.setReturnTransGlideId(returnTransGlideId);//退费交易明细流水ID
				tg.setTxnAdjFlg(AccountContants.TRANSACTION_FLOW_FLAG_NORMAL);// 交易流水标识
				tg.setTxnAmt(bb);// 交易金额--工本费
				tg.setTxnDt(now);// 交易时间
				tg.setTxnTp(AccountContants.TXNTP_COST);// txnTp 交易类型

				tgm.insert(tg);	
				
				
				
				
		vo.setCertNo(ce.getCertNo());
		vo.setBusinessTypeName("批量申请");
		vo.setCorpName(scv.getCorpName());
		vo.setApplyPeopleCount(scv.getNum());
		vo.setTransactionAmount(scv.getFee());
		vo.setOperator(activeUser.getUserNo().toString());
		vo.setNet(activeUser.getBranchName());
		vo.setDate(DateFormatUtils.format(now, "yyyy-MM-dd"));
		vo.setCardpName(scv.getCardPname());
		return vo;
	}

	
	@Override
	public ShowChargeVo showCharge(String path,String applyBatchNo) throws ApplicationException {
		
		String cardProductCode = applyBatchNo.substring(0, 2);
		Date now = new Date();
		FileInputStream f;
		try {
			f = new FileInputStream(path+File.separator+applyBatchNo+".xlsx");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ApplicationException(ErrorCode.OTHER_EXCEPTION, "文件找不到");
		}
		Other o = Excel.validExcel(f);
		
		FeeRulesVo fv= new FeeRulesVo();
		fv.setCardpCode(cardProductCode);
		fv.setFeeType(AccountContants.FEE_TYPE_NOMINAL_FEE);
		fv.setNow(now);
		FeeRules frs = frsm.queryFeeRulesByCardPCodeAndFeeType(fv);
		try{
            System.out.println(frs.getFeeBln());
        }catch(NullPointerException e){
        	e.printStackTrace();
			throw new ApplicationException(ErrorCode.QUERY_DATA_NULL, "未有该产品的工本费或者已过期");
		}
		BigDecimal	unitPrice = frs.getFeeBln();
		BigDecimal	total = unitPrice.multiply(new BigDecimal(o.getNum()));

		
		ShowChargeVo vo = new ShowChargeVo();
		vo.setNum(o.getNum());
		vo.setCardPname(cpdm.queryCardPCode(cardProductCode).getCardpName());
		vo.setCorpName(o.getCorpName());
		vo.setFee(total.toString());
		vo.setApplyBatchNo(applyBatchNo);
		vo.setCardProductCode(cardProductCode);
		vo.setFeeRuleId(frs.getFeeRuleId());
		vo.setFeeRulesId(frs.getFeeRulesId());
		return vo;
	}
	
}
